// 步进格式化
function roundStep (qty, stepSize) {
  stepSize = '' + stepSize
  // Integers do not require rounding
  if (Number.isInteger(qty)) return qty
  const qtyString = parseFloat(qty).toFixed(16)
  const desiredDecimals = Math.max(stepSize.indexOf('1') - 1, 0)
  const decimalIndex = qtyString.indexOf('.')
  return parseFloat(qtyString.slice(0, decimalIndex + desiredDecimals + 1))
}

function formatPrice (price, btbItem) {
  return roundStep(price, btbItem.tick_size || 0)
}

/**
 * @param available 卖出份额
 * @param btbItem 详情
 * @param price 目前价格
 * @returns {*}
 */
function formatMinSell (available, btbItem, price) {
  // 数量太少
  if (available < btbItem.min_qty) {
    return 0
  }
  // 金额太小
  if ((available * price) < (btbItem.min_notional * 1.01)) {
    return 0
  }
  return roundStep(available, btbItem.step_size || 0)
}

/**
 * @param buyUsdt 购买数量
 * @param btbItem 详情
 * @param price 价格
 * @param hasUsdt 持有
 * @returns {*}
 */
function formatMinBuy (buyUsdt, btbItem, price, hasUsdt) {
  let quantity = buyUsdt / price
  // 数量太少
  if (quantity < btbItem.min_qty) {
    return false
  }
  // 金额太小
  if ((buyUsdt) < (btbItem.min_notional * 1.01)) {
    return false
  }
  // 所剩的不够用了
  if (buyUsdt >= hasUsdt * 0.95) {
    return false
  }
  return roundStep(quantity, btbItem.step_size || 0)
}

function getQuantity (asInfo, btbItem, btbIndexConfig) {
  const itemUsdtAll = (btbItem.proportion / btbIndexConfig.proportionAll) * btbIndexConfig.balance.ALL
  if (asInfo.type === 0) {
    // 买入
    // let wantUsdt = itemUsdtAll * asInfo.rate
    // // 超出单币种比例限制
    // if ((wantUsdt + btbItem.usdt) > itemUsdtAll) {
    //   wantUsdt = itemUsdtAll - btbItem.usdt
    // }
    // // 超出剩余usdt
    // if (wantUsdt >= (btbIndexConfig.balance.USDT) * 0.925) {
    //   wantUsdt = (btbIndexConfig.balance.USDT) * 0.925
    // }
    // 买到模式
    let wantUsdt = itemUsdtAll * asInfo.rate
    wantUsdt = wantUsdt - btbItem.usdt
    if (wantUsdt < 0) {
      wantUsdt = 0
    }
    // 超出剩余usdt
    if (wantUsdt >= (btbIndexConfig.balance.USDT) * 0.925) {
      wantUsdt = (btbIndexConfig.balance.USDT) * 0.925
    }
    return formatMinBuy(wantUsdt, btbItem, btbItem.close, btbIndexConfig.balance.USDT)
  } else {
    // 卖出
    let wantUsdt = itemUsdtAll * asInfo.rate
    // 全卖
    if (asInfo.rate === 1) {
      wantUsdt = btbItem.usdt
    }
    // 想卖的超过自己持有的
    if ((btbItem.usdt - wantUsdt) < 0) {
      wantUsdt = btbItem.usdt
    }
    // 如果是bnb
    if (btbItem.code === 'BNB') {
      // 留下总资产的1/100当做手续费
      const sx = btbIndexConfig.balance.ALL * 0.01
      // 剩余的小于需要留下的
      if ((btbItem.usdt - wantUsdt) <= sx) {
        wantUsdt = btbItem.usdt - sx
        if (wantUsdt < 0) {
          wantUsdt = 0
        }
      }
    }
    return formatMinSell(wantUsdt / btbItem.close, btbItem, btbItem.close)
  }
}

module.exports = {
  getQuantity,
  formatMinSell,
  formatMinBuy,
  formatPrice
}
